package cn.bearspark.common.parse.html;

import cn.bearspark.common.parse.Parser;

import java.util.ArrayList;
import java.util.List;

/**
 * span 标签的解析器
 *
 * @author f
 */
public class TagSpanParser extends Parser<HtmlTextParseContext> {
    @Override
    public void parse() {
        HtmlTextParseContext context = pipeline().getContext();
        String src = context.getBody();
        List<String> atUsernameList = new ArrayList<>();
        int index = 0;
        while (true) {
            int openIndex = src.indexOf("<span class=\"username\" contenteditable=\"false\">@", index);
            if (openIndex == -1) {
                context.setAtUsernameList(atUsernameList);
                context.setBody(src);
                return;
            }
            int closeIndex = src.indexOf("</span>", openIndex);
            atUsernameList.add(
                    src.substring(openIndex + "<span class=\"username\" contenteditable=\"false\">@".length(), closeIndex)
            );
            src = src.substring(0, openIndex) +
                  "<s>" +
                  src.substring(closeIndex + "</span>".length());
            index = closeIndex + "</span>".length();
        }
    }

    @Override
    public void unparse() {
        // 这段解析逻辑留给前端，后端无需解析
//        HtmlTextParseContext context = pipeline().getContext();
//        String tar = context.getBody();
//        List<String> atUsernameList = context.getAtUsernameList();
//        if (atUsernameList.isEmpty()) {
//            return;
//        }
//        int index = 0;
//        int atUsernameIndex = 0;
//        while (true) {
//            int openIndex = tar.indexOf("<s>", index);
//            if (openIndex == -1) {
//                context.setBody(tar);
//                return;
//            }
//            tar = tar.substring(0, openIndex) +
//                  "<span class=\"username\" contenteditable=\"false\">@" +
//                  atUsernameList.get(atUsernameIndex++) +
//                  "</span>" +
//                  tar.substring(openIndex + "<s>".length());
//            index = tar.indexOf("</span>", openIndex) + "</span>".length();
//        }
    }
}
